package com.zm.upload.web;

import com.zm.upload.bean.UploadPropertles;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadDo {
    @Autowired
    UploadPropertles propertles;

    @PostMapping("upload")
    Result upload(@RequestParam("file") MultipartFile file,
                  String webPath) throws IOException {
        String filename = file.getOriginalFilename();
        String prefix = UUID.randomUUID().toString();
        System.out.println("filename = " + filename);
        System.out.println("webPath = " + webPath);
        String suffix = "";
        if(filename.contains(".")){
            int i = filename.lastIndexOf(".");
            suffix = filename.substring(i);
        }
        String newFilename = prefix + suffix;
        String disPath = propertles.getMapper()
                //转成流
                .stream()
                //过滤出对应的mapper对象
                .filter(m->m.getWebPath().equals(webPath))
                //提取第一个元素
                .findFirst()
                //获取元素对象
                .get()
                //获取磁盘路径
                .getDiskPath();
        System.out.println("webPath = " + webPath);
        System.out.println("disPath = " + disPath);
        File fileObj = new File(disPath,newFilename);
        file.transferTo(fileObj);
        return new Result(1,"文件上传成功",webPath+newFilename);
    }

    @PostMapping("uploads/**")
    public Result uploads(@RequestParam MultipartFile[] file,
                          HttpServletRequest request) throws IOException {
        System.out.println("request.getServletPath() = " + request.getServletPath());
        System.out.println("request.getRequestURI() = " + request.getRequestURI());
        String path = request.getServletPath();
        String webPath = path.replaceAll("/uploads(/.+)", "$1");
        System.out.println("webPath = " + webPath);
        List<Object> paths = new ArrayList<>();

        for (MultipartFile f : file) {
            Result res = upload(f, webPath);
            paths.add(res);
        }
        return new Result(1,"文件上传成功",paths);
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Result{
    int code;
    String msg;
    Object data;
}
